package com.xw.kotlinlib.network;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;

import java.io.IOException;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 对数据进行简单的预筛选.
 *
 * @author Administrator
 * @date 2019/12/27
 */
final class SGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private static final String CODE_NAME = "code";
    private static final String MSG_NAME1 = "message";
    private static final String MSG_NAME2 = "msg";
    private static final int CODE_SUCCEED = 200;
    private static final int CODE_TOKEN_INVALID = 501;

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    SGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        try {

            if (json.length() == 0) {
                throw new DataException(999, "json string is null", null);
            }

            //采用非黑即白防止误伤
            int code = 200;
            JsonObject jo = gson.fromJson(json, JsonObject.class);
            JsonElement je = jo.get(CODE_NAME);
            if (je != null && je.isJsonPrimitive() && je.getAsJsonPrimitive().isNumber()) {
                code = je.getAsJsonPrimitive().getAsInt();
            }

            //塞入错误信息
            if (code != CODE_SUCCEED) {
                if (code == CODE_TOKEN_INVALID) {
                    //todo 这个地方可以操作token 过期重新登录的功能
//                    LibUserManager.logout(LibServerConfig.INSTANCE.context());
//
//                    List<Activity> list = ActivityStack.getInstance().getActivity();
//                    for (Activity activity :list) {
//                        if (activity != null) {
//                            activity.finish();
//                        }
//                    }
//
//                    Context context = LibServerConfig.INSTANCE.context();
//                    Intent intent = new Intent(context, LoginActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(intent);

                    return null;
                }

                String errorMsg = "";
                JsonElement msg = jo.get(MSG_NAME2);
                msg = msg != null ? msg : jo.get(MSG_NAME1);
                if (msg != null && msg.isJsonPrimitive() && msg.getAsJsonPrimitive().isString()) {
                    errorMsg = msg.getAsJsonPrimitive().getAsString();
                }
                throw new DataException(code, " " + errorMsg, json);
            }

            return adapter.fromJson(json);
        } finally {
            value.close();
        }

    }


}
